#!/bin/bash

Date=$(date +%F)
back_dir=/data/etcd
recover_date=$2
Ip=`ip a|awk 'NR==8{print $2}'|awk -F "/" '{print $1}'`

backup(){
	etcdctl backup --data-dir $back_dir --backup-dir /data/backup_etcd
	tar zcf /data/backup /data/backup_etcd$Date
	[ $? -eq 0 ]&&rm -rf /data/backup_etcd
}

recover(){	
	docker rm -f etcd
	rm -rf /data/etcd
	ETCD_VERSION=v3.0.0
	TOKEN=etcd-cluster1-token
	CLUSTER_STATE=new
	NAME_1=etcd-node-0
	NAME_2=etcd-node-1
	NAME_3=etcd-node-2
	HOST_1=10.25.232.131
	HOST_2=10.24.152.30
	HOST_3=10.47.49.133
	CLUSTER=${NAME_1}=http://${HOST_1}:2380,${NAME_2}=http://${HOST_2}:2380,${NAME_3}=http://${HOST_3}:2380
	if [ $Ip = $HOST_1 ];then
		THIS_NAME=${NAME_1}
	elif [ $Ip = $HOST_2 ];then
		THIS_NAME=${NAME_2}			
	else
		THIS_NAME=${NAME_3}
	fi
	THIS_IP=${Ip}
	docker run -d -v /data/etcd:/data/etcd --net=host -p $HOST_1:2379:2379 -p $HOST_1:2380:2380 --name etcd quay.io/coreos/etcd:${ETCD_VERSION} /usr/local/bin/etcd --data-dir=data.etcd --name ${THIS_NAME} --initial-advertise-peer-urls http://${THIS_IP}:2380 --listen-peer-urls http://0.0.0.0:2380 --advertise-client-urls http://${THIS_IP}:2379 --listen-client-urls http://0.0.0.0:2379 --initial-cluster ${CLUSTER} --initial-cluster-state ${CLUSTER_STATE} --initial-cluster-token ${TOKEN} --data-dir=/data/etcd
	docker stop etcd
	tar zcf /data/backup_etcd${recover_date} && mv /data/backup_etcd/* /data/etcd/
	docker start etcd
}

help(){
	echo "USAGE: sh backup_etcd.sh backup|recover recover_dir"
}

list() {
	backup_list=`ls -lh /data/backup*|awk '{print $9}'`
	echo "The tar package you can choose: ${backup_list}"
}

main(){
	case $1 in
		backup)
			backup
			;;
		recover)
			#recover $2
			;;
		*)
			help
			list
			;;
	esac
}
main
